package flights.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import flights.bi.Ticket;
import flights.db.TicketHandler;

/**
 * Servlet implementation class TicketServlet
 */
public class TicketServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		PrintWriter out = response.getWriter();
		String url = request.getPathInfo();
		response.setContentType( "text/html" ); 
		if (url != null && url.indexOf("get") != -1)
		{
			String bid = request.getParameter("bid");
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
			List<Ticket> tickets = new ArrayList<Ticket>();
			try {
				tickets = TicketHandler.getAllTicketsByBooking(Integer.parseInt(bid));
			} catch (NumberFormatException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			out.print(gson.toJson(tickets));	
		}
		if (url != null && url.indexOf("remove") != -1)
		{
			String ticketID = request.getParameter("tid");
			int nRows = 0;
			try {
				nRows = TicketHandler.deleteBTicketByID(Integer.parseInt(ticketID));
			} catch (NumberFormatException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			out.write("{\"rows\":" + nRows + "}");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String url = request.getPathInfo();
		response.setContentType("text/html"); 
		if (url != null && url.indexOf("update") != -1)
		{
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
			String ticketJson = request.getParameter("ticket");
			if (ticketJson != null && !ticketJson.isEmpty()) {
				
				Type ticketType = new TypeToken<Ticket>(){}.getType();
				Ticket ticket = gson.fromJson(ticketJson, ticketType);
				
				int nRows = 0;
				try {
					nRows = TicketHandler.upsertTicket(ticket);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				out.write("{\"rows\":" + nRows + "}");
			}
		}
	}

}
